
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.BusinessLogic.Common.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.Common;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// Ticket应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class TicketAppService : YozeevAppServiceBase, ITicketAppService
    {
        private readonly IRepository<Ticket, Guid> _entityRepository;

		//private readonly IRepository<TicketListDto, Guid> _ticketRepository;

		private readonly IRepository<Schedule, Guid> _scheduleRepository;

		private readonly IRepository<Wharf, Guid> _wharfRepository;

		private readonly IRepository<Boat, Guid> _boatRepository;

		private readonly IRepository<Route, Guid> _routeRepository;

		private readonly ITicketManager _entityManager;

		private readonly IQueryHelper _queryHelper;

		private readonly IHostingEnvironment _hostingEnvironment;

		/// <summary>
		/// 构造函数 
		///</summary>
		public TicketAppService(
        IRepository<Ticket, Guid> entityRepository
        ,ITicketManager entityManager
			,IRepository<Schedule, Guid> scheduleRepository
			,IRepository<Wharf, Guid> wharfRepository
			,IRepository<Boat, Guid> boatRepository
			, IRepository<Route, Guid> routeRepository
			, IQueryHelper queryHelper
			//, IRepository<TicketListDto, Guid> ticketRepository
			, IHostingEnvironment hostingEnvironment
		)	
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_scheduleRepository = scheduleRepository;
			_wharfRepository = wharfRepository;
			_boatRepository = boatRepository;
			_routeRepository = routeRepository;
			_queryHelper = queryHelper;
			//_ticketRepository = ticketRepository;
			_hostingEnvironment = hostingEnvironment;
        }


        /// <summary>
        /// 获取Ticket的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[HttpPost]
        public async Task<PagedResultDto<TicketListDto>> GetPaged(GetTicketsInput input)
		{
			var expression = _queryHelper.WhereExp<Ticket>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<Ticket>(expression, GetViewTypeEnum<Ticket>(), await GetBranchUser());
			var query = _entityRepository.GetAll().Where(expression);
			// TODO:根据传入的参数添加过滤条件
            

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TicketListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<TicketListDto>>();

			return new PagedResultDto<TicketListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TicketListDto信息
		/// </summary>
		public async Task<TicketListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TicketListDto>();
		}

		/// <summary>
		/// 获取编辑 Ticket
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetTicketForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetTicketForEditOutput();
TicketEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TicketEditDto>();

				//ticketEditDto = ObjectMapper.Map<List<ticketEditDto>>(entity);
			}
			else
			{
				editDto = new TicketEditDto();
			}

			output.Ticket = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改Ticket的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateTicketInput input)
		{

			if (input.Ticket.Id.HasValue)
			{
				await Update(input.Ticket);
			}
			else
			{
				await Create(input.Ticket);
			}
		}


		/// <summary>
		/// 新增Ticket
		/// </summary>
		[AbpAuthorize(TicketPermissions.Create)]
		protected virtual async Task<TicketEditDto> Create(TicketEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <Ticket>(input);
            var entity=input.MapTo<Ticket>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TicketEditDto>();
		}

		/// <summary>
		/// 编辑Ticket
		/// </summary>
		protected virtual async Task Update(TicketEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除Ticket信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除Ticket的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}

		public Task<PagedResultDto<TicketListDto>> GetPagedForSchedule(GetTicketsInput input)
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// 音频上传
		/// </summary>
		/// <param name="file"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<UploadAudioDto> UploadAudioAsync(IFormFile file)
		{
			var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

			var fileName = Path.GetFileName(fileContent.FileName.Trim()).ToString();

			var ext = Path.GetExtension(fileName);

			if (!CheckFileType(ext))
			{
				throw new UserFriendlyException(200, "上传的音频格式错误，请上传格式为bmp, jpg, jpeg, png, gif的文件");
			}

			//保存文件
			var dir = Path.Combine(_hostingEnvironment.WebRootPath, "Audios");

			var newFileName = Guid.NewGuid().ToString() + ext;

			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}

			using (var fileStream = new FileStream(Path.Combine(dir, newFileName), FileMode.Create))
			{
				await file.CopyToAsync(fileStream);
			}

			return new UploadAudioDto { Uri = "Audios/" + newFileName };
		}

		private bool CheckFileType(string ext)
		{
			string[] allowTypes = { "mp3", "wma", "avi", "rm", "rmvb", "flv", "mpg", "mov", "mkv" };
			if (Array.IndexOf(allowTypes, ext.ToLower()) == -1)
			{
				return false;
			}
			return true;
		}

	}
}


